<template>
	<view class="page">
		<form @submit="commitHomework" class="content">
			<!-- 标题 -->
			<view class="title">
				<view class="title_name">
					<text>{{homework.name}}</text>
				</view>
				<view class="title_time">
					<text>授课时间：{{homework.time}}</text>
				</view>
			</view>
			<!-- 课堂反馈 -->
			<view class="feedback" v-if="!homework.overview">
				<view class="feedback_title">
					<image src="../../static/box.png" mode=""></image>
					<text>课堂反馈</text>
				</view>
				<view class="feedback_content" v-if="feedback.content">{{feedback.content}}</view>
				<block v-else>
					<textarea class="contentInput" placeholder="请输入内容" name="feedback" :value="feedback.content"></textarea>
					<!-- 上传图片和视频 -->
					<view class="addMedia" @click="chooseVideoImage('feedback')">
						<image src="../../static/add.png" mode=""></image>
						<text>添加图片或视频</text>
					</view>
				</block>
				<view class="media" v-if="feedback.images.length > 0">
					<image v-for="(item, index) in feedback.images" :key="index" :src="item" mode=""></image>
				</view>
				<view class="media" v-if="feedback.video != ''">
					<video class="video" :src="feedback.video" controls direction="-90"></video>
				</view>
			</view>
			<!-- 作业题目 -->
			<view class="subject">
				<view class="subject_title">
					<image src="../../static/box.png" mode=""></image>
					<text>作业题目</text>
				</view>
				<view class="feedback_content" v-if="homework.subject">{{homework.subject}}</view>
				<textarea v-else class="contentInput" placeholder="请输入内容" name="homeworkSubject" :value="homework.subject"></textarea>
			</view>
			<!-- 截止时间 -->
			<view class="score">
				<image src="../../static/box.png" mode=""></image>
				<text>截止时间</text>
				<picker :disabled="homework.subject" mode="date" name="endTime" :value="endTime" :class="homework.subject ? 'disabled' : 'endTime'" @change="bindTimeChange">
					{{endTime}}
				</picker>
			</view>
			<!-- 作业内容 -->
			<view v-if="type == '学生' && homework.content == ''" class="homeworkInput">
				<view class="subject_title">
					<image src="../../static/box.png" mode=""></image>
					<text>作业</text>
				</view>
				<textarea class="contentInput" placeholder="请输入内容" name="content"></textarea>
				<view class="addMedia" @click="chooseVideoImage('homework')">
					<image src="../../static/add.png" mode=""></image>
					<text>添加图片或视频</text>
				</view>
			</view>
			<view v-if="homework.content != ''" class="homeworkShow">
				<view class="subject_title">
					<image src="../../static/box.png" mode=""></image>
					<text>作业内容</text>
				</view>
				<view class="feedback_content">
					{{homework.content}}
				</view>
			</view>
			<view class="media" v-if="homework.images.length > 0">
				<image :src="homework.images" mode=""></image>
			</view>
			<view class="media" v-if="homework.video != ''">
				<video class="video" :src="homework.video" controls direction="-90"></video>
			</view>
			<!-- 作业评分 -->
			<view v-if="homework.content" class="score">
				<image src="../../static/box.png" mode=""></image>
				<block v-if="type=='教师' || homework.score">
					<text>评分</text>
					<view class="score_content" v-if="homework.score">
						{{homework.score}}
					</view>
					<view v-else class="score_input">
						<input name="score"/>
					</view>
					<text>分</text>
				</block>
				<view v-if="!homework.score && type=='学生'">
					未评分
				</view>
			</view>
			<!-- 作业评语 -->
			<view v-if="homework.content != ''" class="remark">
				<view class="remark_title">
					<image src="../../static/box.png" mode=""></image>
					<text>评语</text>
				</view>
				<view class="feedback_content" v-if="homework.remark">
					{{homework.remark}}
				</view>
				<textarea v-if="!homework.remark && type=='教师'" class="contentInput" placeholder="请输入内容" name="remark"></textarea>
				<view v-if="!homework.remark && type=='学生'" class="remark_content">老师还未点评</view>
			</view>
			<button form-type="submit" class="commitButton" v-if="!homework.score && type == '教师' || !homework.subject || !homework.content">提交</button>
		</form>
	</view>
</template>

<script>
	import cloudbase from '@cloudbase/js-sdk';
	const db = cloudbase.database();
	const dbCmd = db.command;
	let sourceType = [
		['camera'],
		['album'],
		['camera', 'album']
	]
	let openId;
	export default {
		data() {
			return {
				// 用户类型
				type: '',
				// 调取相册,选择图片视频用
				sourceType: ['拍摄', '相册', '拍摄或相册'],
				cameraList: [{
						value: 'back',
						name: '后置摄像头',
						checked: 'true'
					},
					{
						value: 'front',
						name: '前置摄像头'
					},
				],
				sourceTypeIndex: 2,
				cameraIndex: 0,
				// 获取的作业数据
				homework: {
					_id: '',
					name: '',
					time: '',
					subject: '',
					content: '',
					images: [],
					video: '',
					score: '',
					studentId: ''
				},
				// 内容
				answer: '',
				tempFilePaths: [],
				videoSrc: '',
				feedback: {
					images: [],
					video: '',
					content: ''
				},
				endTime: '',
				option: ''
			}
		},
		onUnload() {
			this.src = '',
			this.sourceTypeIndex = 2,
			this.sourceType = ['拍摄', '相册', '拍摄或相册'];
		},
		onLoad(item) {
			openId = getApp().globalData.userInfo.openId;
			this.type = getApp().globalData.userInfo.type;
			if(item.option) this.option = item.option;
			if(item.homework){
				let homework = JSON.parse(item.homework);
				// console.log(homework);
				this.homework.name = homework.name;
				this.homework.time = homework.time;
				this.homework._id = homework._id;
				this.homework.studentId = homework.studentId;
				// 查询是否发布过作业
				if(homework.subject){
					this.feedback = homework.feedback;
					this.endTime = homework.endTime;
					this.homework.subject = homework.subject;
				}else{
					let date = new Date();
					this.endTime = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
				}
				// 查询是否完成了
				if(homework.homework){
					this.homework.content = homework.homework.content;
					this.homework.images = homework.homework.images;
					this.homework.video = homework.homework.video;
					this.homework.score = homework.homework.score;
					this.homework.remark = homework.homework.remark;
				}
			}
		},
		methods: {
			bindTimeChange: function(e){
				console.log(e);
				this.endTime = e.detail.value;
			},
			commitHomework: function(e){
				switch(this.option){
					case '待发起':
						this.initiate(e);
						break;
					case '未完成':
						this.sumitHomework(e);
						break;
					case '未批改':
						this.corrected(e);
				}
			},
			// 批改作业
			corrected: function(e){
				// console.log(e.detail.value.score);
				// console.log(e.detail.value.remark);
				db.collection('class').where({
					_id: this.homework._id
				}).field({homeworkList: true}).get().then(res=>{
					let homeworkList = res.data[0].homeworkList;
					let index = 0;
					homeworkList.forEach(item=>{
						// console.log(item);
						if(item.time == this.homework.time){
							// 寻找当前这份作业
							item.homework.forEach(work=>{
								if(work.openid == this.homework.studentId){
									work.score = e.detail.value.score;
									work.remark = e.detail.value.remark;
									console.log('成功批改作业');
									return;
								}
							})
							return;
						}
						index++;
					})
					console.log(homeworkList);
					console.log(index);
					// 更新评分
					db.collection('class').where({
						_id: this.homework._id
					}).update({
						homeworkList: {
							[index]: homeworkList[index]
						}
					}).then(res=>{
						console.log(res);
						if(res.updated == 1){
							uni.showToast({
								title: '提交成功',
								duration: 1500
							})
							setTimeout(()=>{
								uni.navigateBack({
									delta: 3
								})
							}, 1500)
						}
					})
				})
			},
			// 发布作业
			initiate: function(e) {
				this.feedback.content = e.detail.value.feedback;
				let time = this.homework.time.split(' ');
				// 将作业发布到班级中
				db.collection('class').where({
					_id: this.homework._id
				}).update({
					homeworkList: dbCmd.push({
						name: this.homework.name,
						subject: e.detail.value.homeworkSubject,
						time: this.homework.time,
						feedback: this.feedback,
						endTime: this.endTime,
						homework: [],
						students: []	// 已完成的学生id
					})
				}).then(res=>{
					console.log(res);
					if(res.updated == 1){
						uni.showToast({
							title: '发布成功',
							duration: 1500
						})
						setTimeout(()=>{
							uni.navigateBack({
								delta: 2
							})
						}, 1500)
					}
				})
			},
			// 提交作业
			sumitHomework: function(e){
				console.log(e.detail.value);
				if(e.detail.value.content == null) {
					uni.showToast({
						title: '作业内容不能为空',
						icon: 'none',
						duration: 1500
					})
					return ;
				}
				// 获取所有作业
				db.collection('class').where({
					_id: this.homework._id
				}).field({homeworkList: true}).get().then(res=>{
					let homeworkList = res.data[0].homeworkList;
					let index = 0;
					let date = new Date();
					homeworkList.forEach(item=>{
						if(item.time == this.homework.time){
							item.students.push(openId);
							item.homework.push({
								openid: openId,
								content: e.detail.value.content,
								images: this.homework.images,
								video: this.homework.video,
								time: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate(),
								score: '',
								remark: ''
							})
							return;
						}
						index++;
					})
					console.log(homeworkList);
					// 覆盖原本的作业列表
					db.collection('class').where({
						_id: this.homework._id
					}).update({
						homeworkList: {
							[index]: homeworkList[index]
						}
					}).then(res=>{
						console.log(res);
						if(res.updated == 1){
							uni.showToast({
								title: '提交成功',
								duration: 1500
							})
							setTimeout(()=>{
								uni.navigateBack({
									delta: 2
								})
							}, 1500)
						}
					})
				})
			},
			chooseVideoImage: function(type) {
				uni.showActionSheet({
					title: "选择上传类型",
					itemList: ['图片', '视频'],
					success: (res) => {
						console.log(res)
						if (res.tapIndex == 0) {
							this.chooseImage(type)
						} else {
							this.chooseVideo(type)
						}
					}
				})
			},
			chooseImage: function(type) {
				console.log('chooseImage -->' + type);
				let that = this;
				that.tempFilePaths = [];
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					success(res) {
						that.tempFilePaths = res.tempFilePaths;
						res.tempFilePaths.forEach(item=>{
							that.setImgList(item, type);
						})
					}
				})
			},
			chooseVideo: function(type) {
				console.log('chooseVideo -->' + type);
				this.tempFilePaths = []
				// 上传视频
				console.log('上传视频')
				uni.chooseVideo({
					maxDuration: 60,
					count: 1,
					camera: this.cameraList[this.cameraIndex].value,
					sourceType: sourceType[this.sourceTypeIndex],
					success: (res) => {
						this.tempFilePaths = res.tempFilePath;
						this.setVideoList(res.tempFilePath, type);
					}
				})
			},
			setImgList: function(item, type) {
				console.log(item);
				let that = this;
				let str = that.randomString(3);
				cloudbase.uploadFile({
					cloudPath: "homeworkMedia/" + that.homework.name + "/image/" + str +
						".png",
					filePath: item,
					onUploadProgress: function(progressEvent) {
						let percentCompleted = Math.round((progressEvent.loaded *
							100) / progressEvent.total);
						console.log(percentCompleted);
					}
				}).then(result => {
					console.log(result);
					if(type == 'feedback') that.feedback.images.push(result.fileID);
					if(type == 'homework') that.homework.images.push(result.fileID);
				})
			},
			setVideoList: function(item, type) {
				console.log(item);
				let that = this;
				let str = that.randomString(3);
				cloudbase.uploadFile({
					cloudPath: "homeworkMedia/" + that.homework.name + "/video/" + str +
						".mp4",
					filePath: item,
					onUploadProgress: function(progressEvent) {
						let percentCompleted = Math.round((progressEvent.loaded *
							100) / progressEvent.total);
						console.log(percentCompleted);
					}
				}).then(result => {
					console.log(result);
					if(type == 'feedback') that.feedback.video = result.fileID;
					if(type == 'homework') that.homework.video = result.fileID;
				})
			},
			// 取名用 随机
			randomString: function(e) {
				e = e || 32;
				let t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
				let a = t.length;
				let n = "";
				for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
				return n
			}
		}
	}
</script>

<script module="tools" lang="wxs">
	function subContent(val) {
		if (val == undefined) {
			return '';
		}
		return val.split("（")[0];
	}
	module.exports = {
		sub: subContent
	}
</script>

<style>
	page{
		background-color: #F3F5F7;
	}
	.page {
		width: 750rpx;
		/* height: 1812rpx; */
		/* height: 1020rpx; */
		/* padding-bottom: 60px; */
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
	}

	.content {
		width: 702rpx;
/* 		height: 1716rpx; */
		margin-top: 24rpx;
		margin-right: auto;
		margin-left: auto;
		margin-bottom: 30rpx;
		background-color: #FFFFFF;
		border-radius: 32rpx;
	}

	.title {
		width: 627rpx;
		height: 115rpx;
		margin-top: 26rpx;
		margin-right: auto;
		margin-left: auto;

	}

	.title_name {
		width: 627rpx;
		height: 70rpx;
		line-height: 70rpx;
		font-size: 45rpx;
		color: #222222;
		font-weight: 600;
	}

	.title_time {
		width: 627rpx;
		height: 45rpx;
		line-height: 45rpx;
		font-size: 32rpx;
		color: #666666;
	}

	.feedback {
		width: 662rpx;
		margin-top: 32rpx;
	}

	.feedback_title {
		width: 662rpx;
		height: 42rpx;
		font-size: 30rpx;
		margin-bottom: 20rpx;
	}

	.feedback_title image {
		width: 19rpx;
		height: 42rpx;
		vertical-align: middle;
		margin-right: 21rpx;
	}

	.feedback_content {
		width: 622rpx;
		/* height: 162rpx; */
		line-height: 50rpx;
		margin-bottom: 20rpx;
		margin-left: 40rpx;
		color: #707070;
		font-size: 28rpx;

		/* 多行显示+超出部分省略号替代 */
		text-overflow: -o-ellipsis-lastline;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 4;
		-webkit-box-orient: vertical;
	}

	.media {
		width: 486rpx;
		height: 238rpx;
		margin-left: 40rpx;
		display: inline;
	}

	.media image {
		width: 238rpx;
		height: 238rpx;
		margin-right: 10rpx;
	}

	.video {
		width: 238rpx;
		height: 238rpx;
	}

	.subject {
		width: 662rpx;
		/* height: 213rpx; */
		margin-top: 32rpx;
	}

	.subject_title {
		width: 662rpx;
		height: 42rpx;
		font-size: 30rpx;
		color: #222222;
		line-height: 42rpx;
		margin: 20rpx 0rpx;
	}

	.subject_title image {
		width: 19rpx;
		height: 42rpx;
		vertical-align: middle;
		margin-right: 21rpx;
	}

	.subject_content {
		width: 622rpx;
		height: 162rpx;
		margin-left: 40rpx;
		line-height: 40.5rpx;
		color: #707070;
		font-size: 25rpx;

		/* 多行显示+超出部分省略号替代 */
		text-overflow: -o-ellipsis-lastline;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 4;
		-webkit-box-orient: vertical;
	}

	.homeworkShow {
		width: 662rpx;
	}

	.score {
		display: flex;
		align-items: center;
		width: 662rpx;
		height: 50rpx;
		font-size: 30rpx;
		color: #222222;
		line-height: 50rpx;
		margin: 20rpx 0rpx;
	}

	.score image {
		width: 19rpx;
		height: 42rpx;
		vertical-align: middle;
		margin-right: 21rpx;
	}

	.score_content {
		width: 100rpx;
		height: 50rpx;
		
		margin-left: 28rpx;
		margin-right: 10rpx;
		border-radius: 32rpx;
		background-color: #FD973F;
		text-align: center;
		color: #FFFFFF;
		display: inline-block;
	}
	
	.score_input{
		width: 100rpx;
		height: 50rpx;
		margin-left: 28rpx;
		margin-right: 10rpx;
		border-radius: 32rpx;
		text-align: center;
		border: solid 1px #666;
		display: inline-block;
	}

	.remark {
		width: 662rpx;
		/* height: 212rpx; */
		margin-top: 30rpx;

	}

	.remark_title {
		width: 662rpx;
		height: 42rpx;
		font-size: 30rpx;
		color: #222222;
		line-height: 42rpx;
		margin-bottom: 20rpx;
	}

	.remark_title image {
		width: 19rpx;
		height: 42rpx;
		vertical-align: middle;
		margin-right: 21rpx;
	}

	.remark_content {
		width: 622rpx;
		/* height: 162rpx; */
		/* background-color: #0000FF; */
		margin-left: 40rpx;
		line-height: 40.5rpx;
		color: #707070;
		font-size: 25rpx;

		/* 多行显示+超出部分省略号替代 */
		text-overflow: -o-ellipsis-lastline;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 4;
		-webkit-box-orient: vertical;
	}

	.homeworkInput {
		width: 662rpx;
		/* height: 583rpx; */
	}

	.contentInput {
		width: 622rpx;
		height: 294rpx;
		margin-top: 31rpx;
		margin-bottom: 20rpx;
		margin-left: 25rpx;
		border: 1px solid #999999;
		border-radius: 32rpx;
		padding: 20rpx;
	}

	.addMedia {
		width: 234rpx;
		height: 50rpx;
		margin: 10rpx 0rpx;
		margin-left: 435rpx;
		font-size: 20rpx;
		line-height: 50rpx;
		color: #FD973F;

	}

	.addMedia image {
		width: 50rpx;
		height: 50rpx;
		vertical-align: middle;
		margin-right: 14rpx;
	}

	.commitButton {
		width: 200rpx;
		height: 96rpx;
		margin-top: 30rpx;
		margin-right: auto;
		margin-left: auto;
		background-color: #FD973F;
		border-radius: 32rpx;
		text-align: center;
		color: #FFFFFF;
		font-size: 30rpx;
		line-height: 96rpx;
		margin-bottom: 30rpx;
	}
	
	.endTime {
		border: 1px solid #999999;
		border-radius: 16rpx;
		margin: 10rpx 30rpx;
		padding: 5rpx 30rpx;
		text-align: center;
	}
	
	.disabled{
		margin: 10rpx 30rpx;
		line-height: 50rpx;
		color: #707070;
		font-size: 28rpx;
	}
</style>
